package com.aidl.demo.mvp;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;

/**
 * Created by lingchen on 2018/1/30. 14:51
 * mail:lingchen52@foxmail.com
 */
public class LivePresenter extends BasePresenter<LivePresenter.LiveView> {

    public LivePresenter(LiveView liveView) {
        super(liveView);
    }

    //获取所有节目
    public void loadLiveData(Context context) {
        OkGo.<String>post("http://192.168.1.1:80/")
                .tag(this)
                .cacheKey("http://192.168.1.1:80/")
                .cacheMode(CacheMode.REQUEST_FAILED_READ_CACHE)
                .retryCount(2)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Logger.json(response.body());
                        try {
                            Live liveDatas = JSON.parseObject(response.body(), Live.class);
                            if (liveDatas.getCode() == 0) {
                                getView().loadListSuccess(liveDatas);
                            } else {
                                getView().loadFailed(1);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        onSuccess(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        try {
                            getView().loadFailed(2);
                        } catch (NullPointerException e) {
                            e.printStackTrace();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });

    }

    public class Live {
        private int code;

        public int getCode() {
            return code;
        }

        public void setCode(int code) {
            this.code = code;
        }
    }

    public interface LiveView extends BaseView {
        void loadListSuccess(Live liveDatas);

        void loadFailed(int error);

    }
}
